
var chart = {};
var chartData = [];
var chartCursor;
var chartData;
var cateArray = [];
var cateTotalArray = [];

$(function() {
    $.ajax({
        url : backendPath + '/gate-io/usdt-cny/all',
        success : function(data) {
            chartData = JSON.parse(data);
            main();
        }
    });

});

function main() {
    for (var i in chartData) {
        chartData[i].createdAt = new Date(parseInt(chartData[i].createdAt));
    }
    writeChart();
}

function writeChart() {
    $('#lineChartDiv').empty();
    // SERIAL CHART
    chart = new AmCharts.AmSerialChart();
    chart.pathToImages = "js/images/";
    chart.zoomOutButton = {
        backgroundColor: '#000000',
        backgroundAlpha: 0.15
    };
    chart.dataProvider = chartData;
    chart.categoryField = "createdAt";

    // listen for "dataUpdated" event (fired when chart is rendered) and call zoomChart method when it happens
    chart.addListener("dataUpdated", zoomChart);

    // AXES
    // category
    var categoryAxis = chart.categoryAxis;
    categoryAxis.parseDates = true; // as our data is date-based, we set parseDates to true
    categoryAxis.minPeriod = "mm"; // our data is 10-minutely, so we set minPeriod to MM
    categoryAxis.gridAlpha = 0.15;
    categoryAxis.dashLength = 5;
    categoryAxis.axisColor = "#DADADA";

    // value                
    var valueAxis = new AmCharts.ValueAxis();
    valueAxis.axisAlpha = 0.2;
    valueAxis.dashLength = 5;
    valueAxis.unit = 'RMB';
    chart.addValueAxis(valueAxis);

    // GRAPH
    var graph = new AmCharts.AmGraph();
    graph.title = "red line";
    graph.valueField = "buyRate";
    graph.bullet = "round";
    graph.bulletBorderColor = "#FFFFFF";
    graph.bulletBorderThickness = 2;
    graph.lineThickness = 2;
    graph.lineColor = "#D2F400";
    graph.negativeLineColor = "#0352b5";
    graph.hideBulletsCount = 50; // this makes the chart to hide bullets when there are more than 50 series in selection
    chart.addGraph(graph);

    // CURSOR
    chartCursor = new AmCharts.ChartCursor();
    chartCursor.cursorPosition = "mouse";
    // our data is monthly, so we set minPeriod to MMM
    chartCursor.categoryBalloonDateFormat = "MMM";
    chart.addChartCursor(chartCursor);

    // SCROLLBAR
    var chartScrollbar = new AmCharts.ChartScrollbar();
    chartScrollbar.graph = graph;
    chartScrollbar.scrollbarHeight = 40;
    chartScrollbar.color = "#FFFFFF";
    chartScrollbar.autoGridCount = true;
    chart.addChartScrollbar(chartScrollbar);

    // WRITE
    chart.write("lineChartDiv");
}

// this method is called when chart is first inited as we listen for "dataUpdated" event
function zoomChart() {
    // different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
    chart.zoomToIndexes(chartData.length - 40, chartData.length - 1);
}